package com.jizhi.onework.utils;

import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 极光推送工具类
 *
 * @author wb-zh270168
 */
public class JiGuangPushUtil {

    private static final Logger logger = LoggerFactory.getLogger(JiGuangPushUtil.class);

    /**
     * 两个参数分别填写你申请的masterSecret和appKey
     */
    private static JPushClient jPushClient = new JPushClient("6ea622f620419a0972e26bc1", "8b840f7cede95263c1fb3f86");

    /**
     * 通知推送
     * 备注：推送方式不为空时，推送的值也不能为空；推送方式为空时，推送值不做要求
     *
     * @param alias 推送的标签或别名值
     * @param title 推送的内容
     */
    public static void pushNotice(String alias, String title, String detailJson, Long msgId) {
        PushPayload pushPayload = buildPushObject_all_alias_alert(alias, title, "detail", detailJson, "msgId", msgId);
        try {
            //进行推送，实际推送就在这一步
            PushResult pushResult = jPushClient.sendPush(pushPayload);
            logger.info("通知推送结果 response = {}", JSON.toJSONString(pushResult));
        } catch (Exception e) {
            logger.error("极光通知推送异常 err={}", e);
            e.printStackTrace();
        }
    }

    /**
     * 安卓与ios平台，通过别名推送
     *
     * @param alias   别名
     * @param content 推送内容
     * @param key     拓展字段key值
     * @param value   拓展字段value
     * @return
     */
    public static PushPayload buildPushObject_all_alias_alert(String alias, String content, String key, String value,
                                                              String msgId, Long msgIdValue) {
        return PushPayload.newBuilder()
                .setOptions(Options.newBuilder().setApnsProduction(true).build())
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.alias(alias))
                .setNotification(Notification.newBuilder()
                        .setAlert(content)
                        .addPlatformNotification(AndroidNotification.newBuilder().addExtra(key, value)
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setBadge(5)
                                .setSound("default").addExtra(key, value)
                                .addExtra(msgId, msgIdValue)
                                .build())
                        .build())
                .build();
    }
}
